<?php
namespace App\Services;
use App\DTOS\NeiGouDTO;
use App\Exceptions\ServiceException;
use App\Models\Customer;
use App\Models\Game\GameGoods;
use App\Models\Game\GamePackage;
use App\Models\Game\QqDaWanKa;
use App\Models\Game\Server;
use App\Models\Game\ServerGroup;
use App\Models\VirtualOrder;
use App\DTOS\Admin\VirtualOrderSearchDTO;
use App\DTOS\Admin\VirtualOrderInsertDTO;
use App\DTOS\Admin\VirtualOrderUpdateDTO;
use App\Services\Game\NeigouService;
use App\Utils\MyLog;
use App\Utils\ResponseUtil;
use Illuminate\Support\Facades\DB;

// 虚拟订单
class VirtualOrderService
{
    /**
    * @var  \Illuminate\Database\Eloquent\Builder
    */
    private VirtualOrder $model;
    private NeigouService $NeigouService;

    public function __construct(NeigouService $NeigouService)
    {
        $this->model = new VirtualOrder;
        global $gameArea;
        $this->model->setGameArea($gameArea);
        $this->NeigouService = $NeigouService;
    }

    public function paginate(VirtualOrderSearchDTO $DTO)
    {
        $perPage = $DTO->getLimit();
        $page = $DTO->getPage();
        $model = $this->model;
        /**条件判断**/
        return $model->orderByDesc("id")->paginate($perPage,'*','page',$page);
    }

    /**
    * @param  VirtualOrderInsertDTO $insertDTO
    * @return  int
    */
    public function insert(VirtualOrderInsertDTO $insertDTO){
        $insertDTO->setPushStatus(0);
        $insertDTO->setStatus(0);
        $data = $insertDTO->toArray();
        foreach($data as &$value){
            if (is_array($value)){
                $value= json_encode(array_values($value));
            }
        }
        $data['created_at'] = now();
        unset($data['page']); unset($data['limit']);
        return $this->model->insertGetId($data);
    }

    /**
    * @param  int $id
    * @param  VirtualOrderUpdateDTO $updateDTO
    */
    public function updateById($id,VirtualOrderUpdateDTO $updateDTO)
    {
        $data = $updateDTO->toArray();
        foreach($data as &$value){
            if (is_array($value)){
                $value= json_encode(array_values($value));
            }
        }
        $data['updated_at'] = now();
        unset($data['page']); unset($data['limit']);
        $this->model->where('id',$id)->update($data);
    }

    public function deleteById($id)
    {
        $this->model->where('id',$id)->delete();
    }

    public function deleteByIds($ids)
    {
        if (empty($ids)) return;
        $this->model->whereIn('id',$ids)->delete();
    }

    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|VirtualOrder|null
     */
    public function getById($id)
    {
        return $this->model->where('id',$id)->first();
    }

    /**
     * @param $id
     * @param $status
     * @return bool
     * @throws ServiceException
     */
    public function auth($id,$status)
    {
        $discount=0;
        DB::beginTransaction();
        try {
            $virtualOrder = $this->getById($id);
            if ($virtualOrder->status!==0){
                throw new ServiceException('不能再次审核');
            }
            $orderNo = 'virtual_' . getSnowFlakeId();
            $goodsId = $virtualOrder->goods_id;
            $virtualOrder->status = $status;
            $virtualOrder->order_no = $orderNo;
            $customerid= $virtualOrder->customer_id;
            //查询是否是QQ渠道的玩家
            $customer= Customer::query()->where('id',$customerid)->first();
            MyLog::info('查看是否有信心'.json_encode($customer));
            if($customer){
                $channel_uuid=$customer->channel_uuid;
                $info = QqDaWanKa::query()->where('openid',$channel_uuid)->first();
                if($info){
                    $discount=(int)$info->discount;
                }
            }
            if ($status==1){
                $gameGoods =$this->findConfigIndex($virtualOrder->selectedType,$goodsId) ;
                MyLog::info('商品信息'.json_encode($gameGoods));
                $typeValue = $gameGoods->price_fee;
                $neiGouDTO = new NeiGouDTO();
                $neiGouDTO->setGameArea($virtualOrder->server_id);
                $neiGouDTO->setNumber($virtualOrder->number);
                $neiGouDTO->setRoleId($virtualOrder->role_id);
                $neiGouDTO->setOrderNo($orderNo);
                $neiGouDTO->setGoodsId($goodsId);
                $neiGouDTO->setDiscount($discount);
                $neiGouDTO->setTypeValue($typeValue);
                $neiGouDTO->setIsVirtial(1);//1:虚拟
                try {
                    $this->NeigouService->pushToServer($neiGouDTO);
                    $virtualOrder->push_status = 1;
                } catch (ServiceException $e) {
                    MyLog::info("推送问题导致失败".json_encode($e));
                    $virtualOrder->updated_at = date("Y-m-d H:i:s");
                    $virtualOrder->push_status = -1;
                }
            }
            $virtualOrder->save();
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            throw new ServiceException($e->getMessage());
        }

    }


    //根据包含查询
    //根据包含查询
    public function findConfigIndex( $selectedType,$goodsId)
    {


        if ($selectedType) {
            // 获取 type 字段值
            MyLog::info('分组信息'.json_encode($selectedType));

            $gameGoods = GameGoods::query()->where('channeltype', $selectedType)->find($goodsId);
            // 你可以在这里使用 $type 值
        } else {
            // 处理 ServerGroup 不存在的情况
            // 例如：返回错误信息或设置默认值
            $gameGoods = GameGoods::query()->where('channeltype', 0)->find($goodsId);
        }
        MyLog::info('商品信息'.json_encode($gameGoods));
        return $gameGoods;
    }
}
